package com.jscq.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.acl.User;
import com.atguigu.yygh.model.user.StudentDetail;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jscq.yygh.user.mapper.UserInfoMapper;
import com.jscq.yygh.user.service.StudentDetailService;
import com.jscq.yygh.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private StudentDetailService studentDetailService;

    //手机登入接口
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo中获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断是否为Null
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        // 判断验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        //绑定手机号
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            System.out.println("微信登入");
            userInfo = this.selectWxInfoByOpenId(loginVo.getOpenid());
            UserInfo userInfo2 =this.selectUserInfoByPhone(phone);
            //如果已经用手机号注册过
            if (userInfo2 !=null){
                baseMapper.deleteById(userInfo2.getId());
            }
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        if (userInfo == null){
            //判断是否第一次登入,if phone == null  注册
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo==null) {
                //注册
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        //是否被禁用
        if (userInfo.getStatus()==0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //else login

        //返回登入信息
        //返回用户名
        //返回token
        Map<String, Object> map = new HashMap<>();
        Long userId = userInfo.getId();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("userId",userId);
        System.out.println("userId:"+userId);
        map.put("name", name);
        //jwt token生成
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        System.out.println("token:"+token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoByOpenId(String openid) {
        return baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));
    }

    @Override
    public UserInfo selectUserInfoByPhone(String phone) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        if (userAuthVo.getCertificatesType().equals("学生证")){
            userInfo.setStuCode(userAuthVo.getCertificatesNo());
        }else {
            userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        }
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());

        //进行信息更新
        baseMapper.updateById(userInfo);
    }
    //用户列表
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //通过userInfoQueryVo 获取条件值
        String name = userInfoQueryVo.getKeyword();//用户名称
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //not null
         QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.like("auth_status",authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.gt("create_time",createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.lt("create_time",createTimeEnd);
        }
        //调用mapper
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageParam, wrapper);
        userInfoPage.getRecords().stream().forEach(item->{
            this.packgeUserInfo(item);
        });
        return userInfoPage;
    }
    //锁定
    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue()==0 || status.intValue()==1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packgeUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
//        //根据userid查询就诊人信息
        List<StudentDetail> studentDetailList = studentDetailService.findAllUserId(userId);
        map.put("studentDetailList",studentDetailList);
        return map;

    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public UserInfo selectUserInfoByStuCode(String stuCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("stu_code",stuCode);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;

    }


    //返回显示的对象
    private UserInfo packgeUserInfo(UserInfo userInfo) {
        //认证状态
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //用户状态
        String statusString = userInfo.getStatus().intValue()==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
